package com.foreknow.demo10;

import java.sql.*;

public class DBUtil {
    Connection conn;
    PreparedStatement preparedStatement ;
    ResultSet rs;
    /**
     * 连接数据库
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        //1. 加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");
        //2. 获取连接(Connection)
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/basic2","root","123456");
        return conn;
    }

    //select * from admin where username=? and password=?
    public ResultSet getAll(String sql,Object...values) throws SQLException {
        preparedStatement = conn.prepareStatement(sql);
        for(int i = 0;i<values.length;i++){
            preparedStatement.setObject(i+1, values[i]);
        }
        rs = preparedStatement.executeQuery();
        return rs;
    }

    public boolean update(String sql,Object...values) throws SQLException {
        preparedStatement = conn.prepareStatement(sql);
        for(int i = 0;i<values.length;i++){
            preparedStatement.setObject(i+1, values[i]);
        }
        int a = preparedStatement.executeUpdate();
        return a == 1;
    }

    public void closed() throws SQLException {
        if(rs!=null) {
            rs.close();
        }
        if(preparedStatement!=null) {
            preparedStatement.close();
        }
        if(conn!=null){
            conn.close();
        }
    }

    public static void main(String[] args) {
        DBUtil dbUtil = new DBUtil();
        try {
            dbUtil.getConnection();
            boolean isRight = dbUtil.update("insert into admin(username,password) values(?,?)","suhr","suhr");
            if(isRight) {
                System.out.println("success......");
            }else {
                System.out.println("error......");
            }
//            ResultSet rs = dbUtil.getAll("select * from admin where username = ? and password = ?","tom","123456");
//                        while (rs.next()){
//                            //获取到当前行的第几列
//                            int id = rs.getInt("id");
//                            String username = rs.getString("username");
//                            String password = rs.getString("password");
//                            Admin admin = new Admin();
//                            admin.setId(id);
//                            admin.setUsername(username);
//                            admin.setPassword(password);
//                            System.out.println(admin.getUsername());
//                        }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


}
